package com.gitee.feizns.quickstart.mybatis.plus.plugins.inner.autofill;

import com.baomidou.mybatisplus.annotation.TableField;
import com.gitee.feizns.dynamic.DateUtils;
import com.gitee.feizns.quickstart.mybatis.plus.plugins.inner.autofill.annotation.Now;
import org.apache.ibatis.reflection.MetaObject;

import java.time.temporal.TemporalAccessor;
import java.util.Date;

/**
 * 填充字段为当前时间
 * <p>
 *     如果当前字段指定了填充策略{@link TableField#fill()}且标注了{@link Now}且该字段类型是{@link Long}或{@link Date}{@link TemporalAccessor}将自动填充该字段
 * </p>
 * @author feizns
 * @since 2023/3/4
 */
public class AutoFillNowStrategy implements AutoFillStrategy {
    @Override
    public void fill(String filedName, MetaObject metaObject) {
        if ( metaObject.hasGetter(filedName) ) {
            Class<?> getterType = metaObject.getGetterType(filedName);
            long currentTimeMillis = System.currentTimeMillis();
            if ( getterType == Long.class || getterType == long.class )
                metaObject.setValue(filedName, currentTimeMillis);
            else if ( Date.class.isAssignableFrom(getterType) || TemporalAccessor.class.isAssignableFrom(getterType) )
                metaObject.setValue(filedName, DateUtils.to(currentTimeMillis, getterType));
        }
    }

}
